import json

from flask import Blueprint, request, jsonify
from flask import Response

from .models import connect_to_database

blue = Blueprint('user', __name__)


@blue.route("/api/get_data_by_page/", methods=['GET'])
def get_data_by_page():
    conn, cursor = connect_to_database()
    page = request.args.get("page", 1, type=int)
    size = request.args.get("size", 25, type=int)
    start = (page - 1) * size
    query = "SELECT DISTINCT articlename,ID, author, url_img, intro FROM story_bxg LIMIT %s, %s"
    cursor.execute(query, (start, size))
    results = cursor.fetchall()
    cursor.close()
    conn.close()
    data = []
    for row in results:
        articlename, ID, author, url_img, intro = row
        temp_dict = {
            "articlename": articlename,
            "ID": ID,
            "author": author,
            "url_img": url_img,
            "intro": intro
        }
        data.append(temp_dict)
    return jsonify({"code": 200, "message": "success", "data": data})


@blue.route("/api/get_book_effect/", methods=['GET'])
def book_effect():
    conn, cursor = connect_to_database()
    query = "SELECT DISTINCT id, author, img_url, title FROM male_frequency"
    cursor.execute(query)
    results = cursor.fetchall()
    # 遍历查询结果，将每行数据存储为字典并添加到列表中
    data = []
    for row in results:
        id, author, img_url, title = row
        temp_dict = {
            "id": id,
            "author": author,
            "img_url": img_url,
            "title": title
        }
        data.append(temp_dict)
    cursor.close()
    conn.close()
    # 将列表转换为JSON格式，并返回给前端
    response_data = {
        "code": 200,
        "message": "success",
        "data": data
    }
    # 设置Content-Type头部为UTF-8格式
    return Response(json.dumps(response_data, ensure_ascii=False), content_type='application/json; charset=utf-8')


@blue.route("/api/get_books_total", methods=['GET'])
def get_books_total():
    id = request.args.get('id')  # 获取前端传递的id参数

    conn, cursor = connect_to_database()

    # 使用SELECT语句查询指定id的articlename、url_img、intro和所有chapter_name键对应的id
    sql = "SELECT articlename, url_img, intro, id, chapter_name FROM story_bxg WHERE id=%s"
    cursor.execute(sql, (id,))
    result = cursor.fetchone()

    if result:
        # 解包结果
        articlename, url_img, intro, id, _ = result
        # 使用SELECT语句查询articlename对应的所有chapter_name，并按升序排列
        sql = "SELECT chapter_name, id FROM story_bxg WHERE articlename=%s ORDER BY chapter_name ASC"
        cursor.execute(sql, (articlename,))
        chapters = cursor.fetchall()
        # 提取chapter_name和对应的id
        chapter_names = [{"name": chapter[0], "id": chapter[1]} for chapter in chapters]
        cursor.close()
        conn.close()
        # 构建返回的字典数据
        response_data = {
            "code": 200,
            "msg": "Success",
            "data": {
                "articlename": articlename,
                "url_img": url_img,
                "intro": intro,
                "id": id,
                "chapters": chapter_names
            }
        }
        # 返回结果
        return jsonify(response_data)
    else:
        cursor.close()
        conn.close()
        response_data = {
            "code": 404,
            "msg": "Invalid id"
        }
        return jsonify(response_data)


@blue.route("/api/get_reader_con", methods=["GET"])
def get_reader_con():
    id = request.args.get('id')
    conn, cursor = connect_to_database()
    # 查询指定 id 的小说章节信息和内容
    sql = "SELECT chapter_name, author_content, articlename FROM story_bxg WHERE id=%s"
    cursor.execute(sql, (id,))
    result = cursor.fetchone()
    if result:
        # 解包结果
        chapter_name, author_content, articlename = result
        cursor.close()
        conn.close()
        # 构造 JSON 格式的响应数据
        response_data = {
            "code": 200,
            "msg": "Success",
            "data": {
                "articlename": articlename,
                "chapter_name": chapter_name,
                "author_content": author_content
            }
        }
        # 返回结果
        return jsonify(response_data)
    else:
        cursor.close()
        conn.close()
        response_data = {
            "code": 404,
            "msg": "Invalid id"
        }
        return jsonify(response_data)
